<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>商品介绍</h3>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <!--<el-form-item label="商品编号" prop="goodsNo">
          <el-input v-model="form.goodsNo" placeholder="请输入商品编号" />
        </el-form-item>-->
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品所属类目" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品所属类目" clearable size="small">
            <el-option
              v-for="category in categoryList"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择商品供应商" clearable size="small">
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.supplierId"
              :label="supplier.enterpriseName"
              :value="supplier.supplierId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="提货地址(自提点)" prop="teamId">
          <el-input v-model="form.teamId" placeholder="请输入提货地址(自提点)" />
        </el-form-item>-->
        <el-form-item label="配送时间" prop="deliveryTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.deliveryTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择配送时间">
          </el-date-picker>
        </el-form-item>
        <!--<el-form-item label="商品关键字，采用逗号间隔" prop="keywords">
          <el-input v-model="form.keywords" placeholder="请输入商品关键字，采用逗号间隔" />
        </el-form-item>-->
        <el-form-item label="商品图片" prop="picUrl">
          <el-upload
            :action="uploadPath"
            :show-file-list="false"
            :headers="headers"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="form.picUrl" :src="form.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="宣传画廊">
          <el-upload
            :action="uploadPath"
            :limit="5"
            :headers="headers"
            :file-list="bannersFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleBannersUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card">
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>
        <!--<el-form-item label="商品banner图，采用JSON数组格式" prop="banners">
          <el-input v-model="form.banners" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品简介" prop="brief">
          <el-input v-model="form.brief" placeholder="请输入商品简介" />
        </el-form-item>
        <el-form-item label="是否上架" prop="isOnSale">
          <el-input v-model="form.isOnSale" placeholder="请输入是否上架" />
        </el-form-item>
        <el-form-item label="商品分享朋友圈图片" prop="shareUrl">
          <el-input v-model="form.shareUrl" placeholder="请输入商品分享朋友圈图片" />
        </el-form-item>-->
        <el-form-item label="商品规格" prop="specifications">
          <el-input v-model="form.specifications" type="textarea" placeholder="件 / 个 / 盒" />
        </el-form-item>
        <el-form-item label="零售价格" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价格" />
        </el-form-item>
        <el-form-item label="优惠价格" prop="favorablePrice">
          <el-input v-model="form.favorablePrice" placeholder="请输入优惠价格" />
        </el-form-item>
        <!--<el-form-item label="商品详细介绍，是富文本格式" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入商品详细介绍，是富文本格式" />
        </el-form-item>-->
        <el-form-item label="商品详细介绍">
          <editor v-model="form.detail" :init="editorInit" />
        </el-form-item>
        <el-form-item label="浏览量" prop="browse">
          <el-input v-model="form.browse" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="已销售总量" prop="sales">
          <el-input v-model="form.sales" placeholder="请输入已销售总量" />
        </el-form-item>
        <el-form-item label="佣金类型">
          <el-select v-model="form.brokerageType" placeholder="请选择佣金类型">
            <el-option
              v-for="dict in brokerageTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推广佣金金额" prop="brokeragePrice">
          <el-input v-model="form.brokeragePrice" placeholder="请输入推广佣金金额" />
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input v-model="form.inventory" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="销量" prop="saleCount">
          <el-input v-model="form.saleCount" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="运费" prop="freight">
          <el-input v-model="form.freight" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, exportGoods } from "@/api/module/goods";
import { listCategory } from "@/api/module/category";
import { listSupplier } from "@/api/module/supplier";
import { uploadPath } from "@/api/module/common";
import Editor from '@tinymce/tinymce-vue'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  components: { Editor },
  name: "GoodsEdit",
  data() {
    return {
      uploadPath,
      // 所有类目
      categoryList: [],
      // 所有供应商
      supplierList: [],
      // 是否上架字典
      isOnSaleOptions: [],
      // 佣金类型字典
      brokerageTypeOptions: [],
      // 状态字典
      statusOptions: [],
      // 表单参数
      form: {},
      // 画廊图片展示列表
      bannersFileList: [],
      banners: [],
      // 表单校验
      rules: {
        goodsNo: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        deliveryTime: [
          { required: true, message: "配送时间不能为空", trigger: "blur" }
        ],
        specifications: [
          { required: true, message: "商品规格不能为空", trigger: "blur" }
        ],
        browse: [
          { required: true, message: "浏览量不能为空", trigger: "blur" }
        ],
        sales: [
          { required: true, message: "已销售总量不能为空", trigger: "blur" }
        ],
        brokerageType: [
          { required: true, message: "佣金类型不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      },
      editorInit: {
        language: 'zh_CN',
        height: 450,
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        images_upload_handler: function(blobInfo, success, failure) {
          const form_data = new FormData();
          form_data.set('file', blobInfo.blob());
          axios.post(uploadPath, form_data).then(response => {
            if (response.data.code === 200) {
              success(response.data.url);
            }
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    };
  },
  computed: {
    headers() {
      return {
        'Admin-Token': getToken()
      }
    }
  },
  created() {
    this.initData();
    this.getTDictDatas("module_yes_no").then(response => {
      this.isOnSaleOptions = response.data;
    });
    this.getTDictDatas("module_brokerage_type").then(response => {
      this.brokerageTypeOptions = response.data;
    });
    this.getTDictDatas("module_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    initData() {
      if (this.$route.query.form == null) {
        return
      }
      const form = this.$route.query.form;
      this.form = JSON.parse(form);

      /** 查询所有类目信息 */
      const categoryData = {
        status: 0
      };
      listCategory(categoryData).then(response => {
        this.categoryList = response.rows;
      });
      /** 查询所有供应商信息 */
      const supplierData = {
        status: 1
      };
      listSupplier(supplierData).then(response => {
        this.supplierList = response.rows;
      });

      this.banners = JSON.parse(this.form.banners);
      this.banners.forEach((img, i) => {
        this.bannersFileList.push({
          url: img
        })
      });

      if (this.form.detail != null && this.form.detail != '') {
        this.form.detail = this.Base64.decode(this.form.detail);
      }
    },
    // 是否上架字典翻译
    isOnSaleFormat(row, column) {
      return this.selectDictLabel(this.isOnSaleOptions, row.isOnSale);
    },
    // 佣金类型字典翻译
    brokerageTypeFormat(row, column) {
      return this.selectDictLabel(this.brokerageTypeOptions, row.brokerageType);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      // 调用全局挂载的方法，关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由
      // this.$router.go(-1);
      this.$router.push({ path: '/goods/index' });
    },
    uploadPicUrl(response) {
      this.form.picUrl = response.url
    },
    uploadOverrun() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleBannersUrl(response, file, fileList) {
      if (response.code === 200) {
        this.banners.push(response.url)
      }
      this.form.banners = JSON.stringify(this.banners);
      console.log(this.form.banners);
    },
    handleRemove(file, fileList) {
      for (let i = 0; i < this.banners.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        let url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.url
        }

        if (this.banners[i] === url) {
          this.banners.splice(i, 1)
        }
        this.form.banners = JSON.stringify(this.banners);
        console.log(this.form.banners);
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.detail = this.Base64.encode(this.form.detail);
          if (this.form.goodsId != undefined) {
            updateGoods(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.cancel();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addGoods(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.cancel();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    }
  }
};
</script>

<style>
  .el-card {
    margin-bottom: 10px;
  }
  .avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>
